/*
 * @Author: wangtianyu wangtianyu@lierda.com
 * @Date: 2023-12-05 13:43:42
 * @LastEditors: wangtianyu wangtianyu@lierda.com
 * @LastEditTime: 2023-12-08 15:43:30
 * @FilePath: \kcm_c3_v1_0\lib\Application\Wireless\TcpTest.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "TcpTest.h"

#include "kkgui_base.h"
#include "kkgui_app.h"
#include "kkgui_virt_keyboard.h"

#include "WiFi.h"

char tcp_serverIP[16] = "120.27.247.0"; //欲访问的服务端IP地址
uint16_t tcp_serverPort = 1235;         //服务端口号

WiFiClient tcp_client; //声明一个ESP32客户端对象，用于与服务器进行连接

uint8_t tcp_read_buf[500];

void tcp_client_ip_set(kkui_menu_event_e event, char* tab_name, void* param)
{
    if(event == ENTER_TAG)
    {
        uiVirtKeyboard(tcp_serverIP, "IP Address", 15);
        uiBackAppLoop();
    }
    if(event == LOOP_RUN)
    {
    }
    if(event == BACK_LIST)
    {
    }
}


void tcp_client_port_set(kkui_menu_event_e event, char* tab_name, void* param)
{
    if(event == ENTER_TAG)
    {
        char port_buf[6] = {0};
        sprintf(port_buf, "%d", tcp_serverPort);
        uiVirtKeyboard(port_buf, "IP port", 5);
        sscanf(port_buf, "%d", &tcp_serverPort);
        uiBackAppLoop();
    }
    if(event == LOOP_RUN)
    {
    }
    if(event == BACK_LIST)
    {
    }
}

void tcp_client_loop(kkui_menu_event_e event, char* tab_name, void* param)
{
    if(event == ENTER_TAG)
    {
        memset(tcp_read_buf, 0, 500);
        if (tcp_client.connect(tcp_serverIP, tcp_serverPort) != 1) //尝试访问目标地址
        {
            uiBackAppLoop();
        }
    }
    if(event == LOOP_RUN)
    {
        if(tcp_client.connected())
        {
            int read_len = tcp_client.available();
            if(read_len) //如果有数据可读取
            {
                memset(tcp_read_buf, 0, 500);
                tcp_client.read(tcp_read_buf, read_len); //读取数据到换行符
            }

            uiDisClear(0);
            for(int ret = 0; ret < strlen((char *)tcp_read_buf);)
            {
                uiShowString(1, 10 + 9 * (ret / 21), (char *)tcp_read_buf + ret, 8, 1);
                ret += (strlen((char *)tcp_read_buf + ret) > 21?21:strlen((char *)tcp_read_buf + ret));
            }

            if(uiKeyGetValue(UI_KEY_ENTER_ID) == DOWN)
            {
                tcp_client.write("kake control mini TCP TEST"); //将收到的数据回发
            }
            
            if(uiKeyGetValue(UI_KEY_BACK_ID) == DOWN)
            {
                uiBackAppLoop();
            }
        }
        else
        {
            uiBackAppLoop();
        }
    }
    if(event == BACK_LIST)
    {
        tcp_client.stop(); //关闭客户端
    }
}